package com.konsung.ksdc.manager.advice;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.SuggestionNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/3/18 0018.
 */
public class AdviceActivity extends BaseActivity {
    public static final String ADVICE_ITEM_CLICKED = "advice_item_clicked";

    @Bind(R.id.lv_advice_container)
    ListView lvAdviceContainer;
    @Bind(R.id.btn_add_advice)
    Button btnAddAdvice;
    @Bind(R.id.tab_tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.iv_add_new)
    ImageView ivAddNew;
    @Bind(R.id.ll_empty)
    LinearLayout ivSuggestKon;
    @Bind(R.id.iv_abnormal)
    ImageView ivOpinion;
    @Bind(R.id.tv_abnormal_type)
    TextView tvOpinion;
    @Bind(R.id.tv_abnormal_text)
    TextView tvDeclare;
    @Bind(R.id.btn_go)
    Button btnFlush;
    @Bind(R.id.ptr_resflsh)
    protected PtrFrameLayout ptrFrameLayout;
    private AdviceAdapter mAdapter;
    private List<SuggestionNetBean> suggestionList;
    private ProgressDialog progressDialog;
    private static final int MSG_ADVICE = 1;
    private static final int MSG_ADVICENO = 2;
    private static final int MSG_NETFAIL = 3;
    private static final int MSG_NOOPINION = 5; //没有任何建议
    private NetWifiConnectReceiver wifiReceiver;
    private static final int MSG_SERVERLOST = 4; //服务器访问失败
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ADVICE:
                    progressDialog.hide();
                    ivAddNew.setVisibility(View.VISIBLE);
                    break;
                case MSG_ADVICENO:
                    progressDialog.hide();
                    ivAddNew.setVisibility(View.VISIBLE);
                    break;
                case MSG_NETFAIL:
                    ivAddNew.setVisibility(View.GONE);
                    ivSuggestKon.setVisibility(View.VISIBLE);
                    lvAdviceContainer.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.after_no_wifi);
                    tvOpinion.setText(R.string.wifi_not_well);
                    tvDeclare.setText(R.string.check_your_network);
                    btnFlush.setText(R.string.refresh);
                    break;
                case MSG_SERVERLOST:
                    ivAddNew.setVisibility(View.VISIBLE);
                    ivSuggestKon.setVisibility(View.VISIBLE);
                    lvAdviceContainer.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.after_server_fail);
                    tvOpinion.setText(R.string.get_data_fail);
                    tvDeclare.setVisibility(View.INVISIBLE);
                    btnFlush.setText(R.string.reload);
                    break;
                case MSG_NOOPINION:
                    ivAddNew.setVisibility(View.VISIBLE);
                    ivSuggestKon.setVisibility(View.VISIBLE);
                    lvAdviceContainer.setVisibility(View.GONE);
                    ivOpinion.setImageResource(R.drawable.no_opinion);
                    tvOpinion.setText(R.string.tip_suggestion_no);
                    tvDeclare.setVisibility(View.INVISIBLE);
                    btnFlush.setVisibility(View.INVISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advice);
        ButterKnife.bind(this);

        initView();
        initEvent();
        initData();
    }

    /**
     * 点击事件
     */
    private void initEvent() {
        wifiReceiver = new NetWifiConnectReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(wifiReceiver, filter);
        lvAdviceContainer.setOnItemClickListener(new AdapterView
                .OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int
                    position, long id) {
                if (Constants.isNetConnect) {
                    Intent intent = new Intent(AdviceActivity.this,
                            AdviceDetailActivity.class);
                    intent.putExtra(ADVICE_ITEM_CLICKED, suggestionList.get(position));
                    startActivity(intent);
                } else {
                    ToastUtils.toastContent(AdviceActivity.this, getString(R
                            .string.tip_check_net));
                }
            }
        });

        if (ivAddNew != null) {
            ivAddNew.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Constants.isNetConnect) {
                        Intent intent = new Intent(AdviceActivity.this,
                                AddAdviceActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtils.toastContent(AdviceActivity.this, getString(R
                                .string.tip_check_net));
                    }
                }
            });
        }

        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnFlush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Constants.isNetConnect) {
                    ToastUtils.toastContent(AdviceActivity.this, getString(R
                            .string.tip_check_net));
                    return;
                }
                //重新加载
                initData();
//                onResume();
            }
        });
        //刷新控件事件
        initPtr();
    }

    /**
     * 刷新数据
     */
    private void initPtr() {
        /**
         * 经典 风格的头部实现
         */
        final PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(this);
        header.setPadding(0, PtrLocalDisplay.dp2px(15), 0, 0);
        header.setBackgroundResource(R.color.refresh_bg);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {

            //需要加载数据时触发
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptrFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新数据
                        refreshData();
                    }
                }, 1800);
            }

            /**
             * 检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
             */
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }

    /**
     * 重新刷新数据
     */
    private void refreshData() {
        if (!RequestUtils.checkNetwork(AdviceActivity.this)) {
            //刷新停止
            ptrFrameLayout.refreshComplete();
            handler.sendEmptyMessage(MSG_NETFAIL);
            return;
        }

        // ### 网络获取数据 ###
        RequestUtils.findSuggestionByEmpId(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        //刷新停止
                        ptrFrameLayout.refreshComplete();
                        handler.sendEmptyMessage(MSG_SERVERLOST);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        //刷新停止
                        ptrFrameLayout.refreshComplete();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            suggestionList = responseBean.getList(new
                                    TypeToken<List<SuggestionNetBean>>() {
                            }.getType());
                            if (suggestionList.size() > 0) {
                                ivSuggestKon.setVisibility(View.GONE);
                                lvAdviceContainer.setVisibility(View.VISIBLE);
                                mAdapter.refreshData(suggestionList);
                            } else {
                                handler.sendEmptyMessage(MSG_NOOPINION);
                            }
                            handler.sendEmptyMessage(MSG_ADVICE);
                        }
                    }
                });
    }

    /**
     * 初始化
     */
    private void initView() {
        tvTitle.setText(R.string.title_advice);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //网络断开，显示UI
        if (!RequestUtils.isNetworkConnected(this)) {
            handler.sendEmptyMessage(MSG_NETFAIL);
            return;
        }
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage(getString(R.string.dialog_tip_loading));
            progressDialog.setCancelable(true);
            progressDialog.show();
        } else {
            progressDialog.show();
        }

        if (!RequestUtils.checkNetwork(AdviceActivity.this)) {
            hideDialog();
            return;
        }

        // ### 网络获取数据 ###
        RequestUtils.findSuggestionByEmpId(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        handler.sendEmptyMessage(MSG_SERVERLOST);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            suggestionList = responseBean.getList(new
                                    TypeToken<List<SuggestionNetBean>>() {
                                    }.getType());
                            if (suggestionList.size() > 0) {
                                ivSuggestKon.setVisibility(View.GONE);
                                lvAdviceContainer.setVisibility(View.VISIBLE);
                                mAdapter = new AdviceAdapter(suggestionList);
                                lvAdviceContainer.setAdapter(mAdapter);
                            } else {
//                                ivSuggestKon.setVisibility(View.VISIBLE);
                                handler.sendEmptyMessage(MSG_NOOPINION);
                            }
                            handler.sendEmptyMessage(MSG_ADVICE);
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    /**
     * 隐藏dialog
     */
    public void hideDialog() {
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(wifiReceiver);
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_advice);
    }

    /**
     * wifi广播
     */
    public class NetWifiConnectReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Constants.isNetConnect = RequestUtils.isNetworkConnected(MyApplication.getContext());
            if (!Constants.isNetConnect) {
                //网络连接，重新获取数据
                handler.sendEmptyMessage(MSG_NETFAIL);
            }
        }
    }
}
